import {
  ActivatedRouteSnapshot,
  CanActivate,
  CanActivateChild,
  Route,
  Router,
  RouterStateSnapshot
} from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { UniversalService } from '../util/universal.service';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(
    private authService: AuthService,
    private universalService: UniversalService,
    private router: Router
  ) {}

  can(): Observable<any> | Promise<boolean> | boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      setTimeout(() => this.router.navigate(['/entry']), 10);
      return false;
    }
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    this.universalService.pushRouteHistory(state.url);
    return this.can();
  }

  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    this.universalService.pushRouteHistory(state.url);
    return this.can();
  }

  canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
    return this.can();
  }
}
